package client.dialog;

import common.bodies.FriendShipBody;
import common.bodies.UserBody;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;

import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class InviteFriendDialog {

        public static void show(List<FriendShipBody> allFriends, List<String> groupMemberNames, UserBody currentUser, Consumer<List<String>> onConfirm) {
                Dialog<List<String>> dialog = new Dialog<>();
                dialog.setTitle("邀请好友进群");
                dialog.setHeaderText("选择要邀请的好友");

                dialog.getDialogPane().getStylesheets().add(
                        InviteFriendDialog.class.getResource("/css/dialog.css").toExternalForm()
                );
                dialog.getDialogPane().getStyleClass().addAll("custom-dialog", "blue");


                ButtonType confirmButtonType = new ButtonType("邀请", ButtonBar.ButtonData.OK_DONE);
                dialog.getDialogPane().getButtonTypes().addAll(confirmButtonType, ButtonType.CANCEL);

                VBox vbox = new VBox(10);
                vbox.setPadding(new Insets(10));
                dialog.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);


                // 创建 CheckBox 列表
                List<CheckBox> checkBoxes = allFriends.stream()
                        .filter(friend -> {
                                String friendName = friend.getUser1Name().equals(currentUser.getName()) ? friend.getUser2Name() : friend.getUser1Name();
                                return !groupMemberNames.contains(friendName); // 排除群成员
                        })
                        .map(friend -> {
                                String friendName = friend.getUser1Name().equals(currentUser.getName()) ? friend.getUser2Name() : friend.getUser1Name();
                                return new CheckBox(friendName); // 创建 CheckBox
                        })
                        .collect(Collectors.toList());

                vbox.getChildren().addAll(checkBoxes);
                dialog.getDialogPane().setContent(new ScrollPane(vbox)); // 添加到对话框内容中

                // 设置按钮结果转换
                dialog.setResultConverter(dialogButton -> {
                        if (dialogButton == confirmButtonType) {
                                return checkBoxes.stream()
                                        .filter(CheckBox::isSelected)
                                        .map(CheckBox::getText)
                                        .collect(Collectors.toList());
                        }
                        return null;
                });

                // 弹出对话框
                Optional<List<String>> result = dialog.showAndWait();
                result.ifPresent(onConfirm); // 如果确认，触发回调
        }
}
